<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\Detail;
use App\Models\Cart;
use App\Models\Goods;
use App\Models\Order;
use App\Traits\ApiResponse;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Match;

class CommentController extends Controller
{

    use ApiResponse;

    /**
     * [description]
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     * @author: cuibo 2021/4/13 18:59
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'details' => 'required|string|max:65535',
            'order_id' => 'required|int',
        ], [
        ]);
        if (Comment::query()->where('order_id', $request['order_id'])->first()) {
            return $this->error('订单已评论');
        }
        $user = $request->user();
        $order = Order::query()->with('goodsDetails')
            ->where('order_id', $request['order_id'])
            ->where('user_id', $user->id)
            ->first();

        if (!$order) {
            return $this->error('订单不存在');
        }
        foreach ($order->goodsDetails as $goodsDetail) {
            Comment::query()->create([
                'details' => $request['details'],
                'user_id' => $user->id,
                'order_id' => $request['order_id'],
                'goods_id' => $goodsDetail->goods_id,
                'time' => (new Carbon())->toDateString(),
            ]);
        }
        return $this->success([], '评论成功');

    }

    public function getList(Request $request)
    {
        $this->validate($request, [
            'goods_id' => 'required|int',
        ], [
        ]);
        $list = Comment::query()->with('user')->where('goods_id', $request['goods_id'])->paginate();
        return $this->success(['data' => $list]);
    }
}
